<template>
    <view class="container">
        <view class="auth-form">
            <view class="form-title">实名认证</view>

            <view class="upload-section" style="margin-bottom: 20rpx;">
                <view class="upload-item">
                    <view class="upload-title require">证件人像照片</view>
                    <view class="upload-box" @tap="chooseImage('idCardFront')">
                        <image v-if="form.idCardFront" :src="form.idCardFront" mode="aspectFit" />
                        <text v-else class="upload-tip">点击上传</text>
                    </view>
                </view>
                <view class="upload-item">
                    <view class="upload-title require">证件国徽照片</view>
                    <view class="upload-box" @tap="chooseImage('idCardBack')">
                        <image v-if="form.idCardBack" :src="form.idCardBack" mode="aspectFit" />
                        <text v-else class="upload-tip">点击上传</text>
                    </view>
                </view>
                <view class="upload-item">
                    <view class="upload-title">银行卡正面照片</view>
                    <view class="upload-box" @tap="chooseImage('bankCardFront')">
                        <image v-if="form.bankCardFront" :src="form.bankCardFront" mode="aspectFit" />
                        <text v-else class="upload-tip">点击上传</text>
                    </view>
                </view>
            </view>

            <!-- 身份证信息 -->
            <view class="form-section">
                <view class="form-item">
                    <text class="label require">证件类型</text>
                    <view class="picker_con">
                        <picker @change="cardTypeChange" :range="cardTypeList" range-key="label">
                            <view class="picker_val">
                                {{form.idCardType ? getTypeLabel(form.idCardType): '请选择证件类型'}}
                            </view>
                        </picker>
                    </view>
                </view>
                <view class="form-item">
                    <text class="label require">姓名</text>
                    <input type="text" v-model="form.realName" placeholder="真实姓名，上传证件照自动识别" :disabled="realStatus" />
                </view>
                <view class="form-item">
                    <text class="label require">身份证号</text>
                    <input type="text" v-model="form.idCard" placeholder="身份证号码，上传证件照自动识别" :disabled="realStatus" />
                </view>
                <view class="form-item">
                    <text class="label require">证件地址</text>
                    <input type="text" v-model="form.address" placeholder="证件地址，上传证件照自动识别" :disabled="realStatus" />
                </view>
                <view class="form-item">
                    <text class="label require">性别</text>
                    <view class="radio-group">
                        <radio-group @change="radioChange" class="flex-v-center">
                            <label class="flex-center mar-r30">
                                <radio value="01" :checked="form.sex == '01'" />
                                <view>男</view>
                            </label>
                            <label class="flex-center">
                                <radio value="00" :checked="form.sex == '00'" />
                                <view>女</view>
                            </label>
                        </radio-group>
                    </view>
                </view>
            </view>

            <!-- 银行卡信息 -->
            <view class="form-section">
                <view class="form-item">
                    <text class="label">开户银行</text>
                    <input type="text" v-model="form.bankName" placeholder="开户银行，上传银行卡自动识别" />
                </view>
                <view class="form-item">
                    <text class="label">银行卡号</text>
                    <input type="text" v-model="form.bankCard" placeholder="银行卡号，上传银行卡自动识别" />
                </view>
            </view>

            <button v-if="!realStatus" class="submit-btn" @tap="submitAuth">提交认证</button>
            <!-- <agreement v-model="agreeFlag" type="-9" title="用户隐私协议">《用户隐私协议》 </agreement> -->
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { apiList } from '@/api/base';
import { getLoginStatus } from '@/hooks/login';
import { editUserRealAuth, ktIdCardIocr, checkRentUserStatus } from '@/api/user';
import Interact from '@/utils/interact';
import validateIdCard from '@/hooks/checkIdCard'
import { useStore } from 'vuex';
import { onLoad } from '@dcloudio/uni-app';
import agreement from '@/components/base/agreement.vue';
const Store = useStore();


const agreeFlag = ref(true);
let pageFrom = ''
const realStatus = ref(false)
onLoad((options: any) => {
    if(options.from) {
        pageFrom = options.from;
    }

    getLoginStatus().then(state => {
        if(state) {
            checkRentUserStatus({}).then(res =>{
                let realNameInfo = res.data.realNameInfo;
                realStatus.value = realNameInfo && realNameInfo.realStatus == '01'

                form.value.idCardType = realNameInfo.FIdCardType || 'sfz';
                form.value.realName = realNameInfo.realName;
                form.value.idCard = realNameInfo.cardId;
                form.value.sex = realNameInfo.FSex;
                form.value.address = realNameInfo.cardAddress;
                form.value.idCardFront = realNameInfo.imgUrl;
                form.value.idCardBack = realNameInfo.backImgUrl;
                form.value.bankCardFront = realNameInfo.FBankImg;

                form.value.bankName = realNameInfo.FBankName;
                form.value.bankCard = realNameInfo.FBankNo;
            })
        }
    })
})

const cardTypeList = ref([
    { value: 'sfz', label: '中国居民身份证' },
    { value: 'gajmjzz', label: '港澳居民居住证' },
    { value: 'twjmjzz', label: '台湾居民居住证' },
    { value: 'gajmlwndtxz', label: '港澳居民来往内地通行证（回乡证）' },
    { value: 'twjmlwdltxz', label: '台湾居民来往大陆通行证（台胞证）' },
    { value: 'wgryjjljzz', label: '外国人永久居留身份证' },
    { value: 'hz', label: '国际护照' },
])

const cardTypeChange = (e: any) => {
    form.value.idCardType = cardTypeList.value[e.detail.value].value
}
const getTypeLabel = (value: string) => {
    const item = cardTypeList.value.find(item => item.value == value);
    return item ? item.label : '';
}

const form = ref({
    realName: '',
    idCard: '',
    sex: '',
    address: '',
    idCardType: 'sfz',
    idCardFront: '',
    idCardBack: '',

    bankName: '',
    bankCard: '',
    bankCardFront: '',
});



type UploadType = 'idCardFront' | 'idCardBack' | 'bankCardFront' ;
// 选择图片
const chooseImage = (type: UploadType) => {
    if(realStatus.value) return;
    uni.chooseImage({
        count: 1,
        success: (res) => {
            // 检查文件大小
            const tempFilePath = res.tempFilePaths[0];
            uni.getFileInfo({
                filePath: tempFilePath,
                success: (fileInfo) => {

                    // 检查文件大小是否超过2M (2 * 1024 * 1024 bytes)
                    if (fileInfo.size > 6 * 1024 * 1024) {
                        Interact.toast('图片大小不能超过6M');
                        return;
                    }
                    uploadFile(tempFilePath, type);
                },
                fail: () => {
                    Interact.toast('获取文件信息失败');
                }
            });
        }
    });
};

// 上传文件
const uploadFile = (filePath: string, type: UploadType) => {
    uni.uploadFile({
        url: apiList.uploadFileToTencent,
        filePath: filePath,
        name: 'file',
        formData: {
            fileType: 'realAuth',
            fileName: 'file',
            prifix: 'auth',
            merNo: Store.state.shop.merNo,
            token: Store.state.user.account.token,
        },
        success: (uploadFileRes) => {
            let res = JSON.parse(uploadFileRes.data)
            console.log(res);
            if(res.code == 1) {
                form.value[type] = res.data.url;

                if(type == 'idCardBack' || form.value.idCardType != 'sfz') return;
                AIOCRAuthInfo(res.data.url, {
                    'idCardFront':'cardId',
                    'idCardBack':'cardId',
                    'bankCardFront':'bankNo',
                }[type] as AIType)
            }
        },
        fail: (err: any) => {
            Interact.modal(err.data.msg)
        }
    });
};

type AIType = 'cardId' | 'bankNo'
const AIOCRAuthInfo = (imgUrl: string, type: AIType ) => {
    ktIdCardIocr({
        iocrType: type,
        imgUrl
    }).then(res => {
        if(type == 'cardId') {
            form.value.realName = res.data.name || '';
            form.value.idCard = res.data.idNo || '';
            form.value.sex = res.data.sex == '女' ? '00' : '01';
            form.value.address = res.data.address || '';
        }
        if(type == 'bankNo') {
            form.value.bankName = res.data.bankInfo || '';
            form.value.bankCard = (res.data.cardNo || '').replace(/\s/ig, '');
            if(res.data.bankInfo.indexOf('招商') > -1) {
                Interact.modal('目前不支持招商银行卡，请跟换其他银行卡').then(() => {
                    form.value.bankName = '';
                    form.value.bankCard = '';
                    form.value.bankCardFront = '';
                })
            }
        }
    })
}

const radioChange = (e: any) => {
    form.value.sex = e.detail.value;
};



// 提交认证
const submitAuth = () => {
    // 表单验证
    if(!form.value.idCardFront) return Interact.toast('请上传身份证正面照片');
    if(!form.value.idCardBack) return Interact.toast('请上传身份证反面照片');
    if(!form.value.realName) return Interact.toast('请输入姓名');
    if(!form.value.idCard) return Interact.toast('请输入身份证号');
    if(form.value.idCardType == 'sfz') {
        if(!validateIdCard(form.value.idCard)) return Interact.toast('身份证号码有误，请检查后提交');
    }
    // if(!form.value.bankName) return Interact.toast('请输入开户银行');
    // if(!form.value.bankCard) return Interact.toast('请输入银行卡号');
    // if(!form.value.bankCardFront) return Interact.toast('请上传银行卡正面照片');
    editUserRealAuth({
        imgUrl: form.value.idCardFront,
        backImgUrl: form.value.idCardBack,
        cardAddress: form.value.address,
        cardId: form.value.idCard,
        idCardType: form.value.idCardType,
        realName: form.value.realName,
        sex: form.value.sex,
        bankImg: form.value.bankCardFront,
        bankName: form.value.bankName,
        bankNo: form.value.bankCard,
    }).then(async res =>{
        await Interact.modal('认证提交成功');
        if(pageFrom == 'order') {
            uni.redirectTo({
                url: '/pages/user/relationList?from=order',
            })
        } else {
            uni.navigateBack();
        }
    })
};
</script>

<style lang="scss">
.require{
    &:after {
        content: '*';
        color: red;
        margin-left: 4rpx;
    }
}
.container {
    min-height: 100vh;
    background-color: #f8f8f8;
    padding: 15rpx;
}

.auth-form {
    background: #fff;
    border-radius: 16rpx;
    padding: 15rpx;

    .form-title {
        font-size: 36rpx;
        font-weight: bold;
        text-align: center;
        margin-bottom: 40rpx;
    }

    .form-section {
        margin-bottom: 40rpx;

        .section-title {
            font-size: 32rpx;
            font-weight: bold;
            margin-bottom: 20rpx;
        }
    }

    .form-item {
        display: flex;
        align-items: center;
        margin-bottom: 15rpx;
        .picker_con{
            flex: 1;
            height: 70rpx;
            border: 1rpx solid #ddd;
            border-radius: 8rpx;
            .picker_val{
                height: 70rpx;
                line-height: 70rpx;
                padding: 0 10rpx;
                width: 500rpx;
            }

        }
        .label {
            width: 160rpx;
            font-size: 28rpx;
        }

        input {
            flex: 1;
            height: 70rpx;
            border: 1rpx solid #ddd;
            border-radius: 8rpx;
            padding: 0 20rpx;
            font-size: 28rpx;
        }
    }

    .upload-section {
        display: flex;
        justify-content: space-between;
        margin-top: 30rpx;

        .upload-item {
            width: 32%;

            .upload-title {
                font-size: 26rpx;
                margin-bottom: 10rpx;
                text-align: center;
            }

            .upload-box {
                width: 100%;
                height: 130rpx;
                border: 1rpx dashed #ddd;
                border-radius: 8rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                background: #f8f8f8;

                image {
                    width: 100%;
                    height: 100%;
                }

                .upload-tip {
                    font-size: 26rpx;
                    color: #999;
                }
            }
        }
    }

    .submit-btn {
        width: 100%;
        height: 88rpx;
        background: #dda62f;
        color: #fff;
        border-radius: 44rpx;
        font-size: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 60rpx;
    }
}
</style>
